import os
import os.path
from s2c.engine.system_info import SystemInfo
from s2c.rules.conf import FIELD_DELIMITER,SYS_BASE,SYS_CURRENT
from s2c.engine.db_helper import DbHelper
from s2c.tools.utils import get_json_file


# DbImport 将 json 导入数据库
class DbImport:
    def __init__(self):
        self.list = None
        self.fields = None
        self.table_name = None
        self.db = DbHelper()

    # 将 json 文件导入到系统中
    def import_json(self, json_file):
        self.list = None
        self.fields = None
        self.table_name = None
        if not os.path.exists(json_file):
            print(json_file + "文件不存在")
            return False
        # 解析系统JSON文件
        try:
            data = get_json_file(json_file)
        except Exception as e:
            print(f'解析文件{json_file}文件出错', str(e))
            return False

        if not data:
            print(f'解析文件{json_file}文件出错')
            return False
        if not data.__contains__('info'):
            print(f'解析文件{json_file}文件出错, 没有 info 字段')
            return False
        if not data.__contains__('list'):
            print(f'解析文件{json_file}文件出错, 没有 list 字段')
            return False
        info = data['info']
        if not info.__contains__('table_name'):
            print(f'解析文件{json_file}文件出错, 没有 info.table_name 字段')
            return False
        if not info.__contains__('fields'):
            print(f'解析文件{json_file}文件出错, 没有 info.fields 字段')
            return False

        self.table_name = info['table_name']
        self.fields = info['fields']
        self.list = data['list']

        self.batch_insert()
        return True

    # 批量插入数据
    def batch_insert(self):
        table_name = self.table_name
        fields = self.fields.split(FIELD_DELIMITER)
        items = []
        for item in self.list:
            row = tuple(item.split(FIELD_DELIMITER))
            items.append(row)
            # print('row=', len(row), row)
        num = len(fields)
        # ? 问号占位符
        place_holder = []
        for i in range(num):
            place_holder.append('?')

        # 添加 ignore，是将原有的条目忽略掉
        insert_cmd = f'insert or ignore into {table_name} ({", ".join(fields)}) values ({", ".join(place_holder)})'
        # print('batch_insert: ', insert_cmd)
        self.db.batch_insert(insert_cmd, items)


# end class


# 将所有的数据导入， 先扫描/下载后，再
def import_all(dict_type=SYS_CURRENT):
    info = SystemInfo()
    importer = DbImport()
    # 导入基础库前要先清空
    if dict_type == SYS_BASE:
        importer.db.init()  # 清除原有db文件

    importer.import_json(info.file_name(dict_type=dict_type))
    importer.import_json(info.process_name(dict_type=dict_type))

    # 将迁移系统与目标系统不相同，目标系统的指纹库也要
    if dict_type == SYS_BASE and info.need_target():
        importer.import_json(info.file_name(is_target=True, dict_type=dict_type))
        importer.import_json(info.process_name(is_target=True, dict_type=dict_type))


if __name__ == "__main__":
    import_all(SYS_BASE)
    import_all(SYS_CURRENT)
